package com.seari.service.Impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.seari.bean.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.google.gson.Gson;
import com.seari.commonutils.redis.JedisUtilProxy;
import com.seari.commonutils.redis.ex.JedisNotInitializeException;
import com.seari.mapper.FaultMapper;
import com.seari.service.FaultService;
import com.seari.service.LocationService;
import com.seari.utils.GuavaCacheUtil;
import com.seari.utils.HandlerNullUtils;

import redis.clients.jedis.Jedis;

@Service("faultService")
//@Transactional  动态数源混合操作不支持事务   可以增加一层  单独操作各自的事务  
public class FaultServiceImpl implements FaultService {

    @Autowired
    private FaultMapper faultMapper;
    
    @Autowired
    private LocationService locationService;

    @Override
    @DS("slave_1")
    public FaultNum getFaultNum() {

        return faultMapper.getFaultNum();
    }

    @Override
    @DS("master")
    public FaultInfo getRtFaultInfoById(String faultId) {

        FaultInfo faultInfo = faultMapper.getRtFaultInfoById(faultId);
        if(!HandlerNullUtils.objectIsNull(faultInfo)) {
        	  Integer strNum = faultMapper.getRtFaultInfoPeopleNumById(faultId);
              faultInfo.setDisposePeopleNum(strNum+"");
              locationService.fillLocationOfFaultInfoSingle(faultInfo);
              
              if(HandlerNullUtils.objectIsNull(faultInfo.getUserName())) {
            	  faultInfo.setDisposePeopleNum("--");
              }
              if(HandlerNullUtils.objectIsNull(faultInfo.getLeaderPhone())) {
            	  faultInfo.setLeaderPhone("--");
              }
              if(HandlerNullUtils.objectIsNull(faultInfo.getFaultTime())) {
            	  faultInfo.setFaultTime("--");
              }
              if(HandlerNullUtils.objectIsNull(faultInfo.getFaultContent())) {
            	  faultInfo.setFaultContent("--");
              }
        }
      
        return faultInfo;
    }

    @Override
    @DS("slave_1")
    public FaultInfo getRtFaultInfoByIdFromFlow(String faultId) {

        FaultInfo faultInfo = faultMapper.getRtFaultInfoByIdFromFlow(faultId);
      
        if(!HandlerNullUtils.objectIsNull(faultInfo)) {
        	faultInfo.setDisposePeopleNum("--");
        	locationService.fillLocationOfFaultInfoSingle(faultInfo);
        }
        return faultInfo;
    }

    @Override
    @DS("slave_2")
    public FaultInfo getHisFaultInfoById(String faultId) {
        FaultInfo faultInfo = faultMapper.getHisFaultInfoById(faultId);
        
	        if (!HandlerNullUtils.objectIsNull(faultInfo)) {
	        	
	        	   //线路
		        if(!HandlerNullUtils.objectIsNull(faultInfo.getFaultLine())) {
		        	Jedis jedis = null;
		            try {
		                jedis = JedisUtilProxy.getJedis();
		            } catch (JedisNotInitializeException e) {
		                e.printStackTrace();
		            }
		            String lineObjectJsonString = jedis.get("lineInfoList");
		            jedis.close();
		            List<LineInfo> list = JSONArray.parseArray(lineObjectJsonString, LineInfo.class);
		            for (LineInfo lineInfo : list) {
		            	String str = lineInfo.getLineId();
		            	int l = Integer.parseInt(str);
		            	if((l +"").equals(faultInfo.getFaultLine())) {
		            		faultInfo.setFaultLine(lineInfo.getLineName());
		            	}
		            }
		        }else {
		    		faultInfo.setFaultLine("--");
		    	}
		        
		        if(HandlerNullUtils.objectIsNull(faultInfo.getFaultContent())) {
		        	faultInfo.setFaultContent("--");
		        }
		        
		        if(HandlerNullUtils.objectIsNull(faultInfo.getZy())) {
		        	faultInfo.setZy("--");
		        }
		        
		        if(HandlerNullUtils.objectIsNull(faultInfo.getBx())) {
		        	faultInfo.setBx("--");
		        }
		        
		        //故障设备
	            if (!HandlerNullUtils.objectIsNull(faultInfo.getGzSb())) {
	            	String sbN = "";
	            	if(!HandlerNullUtils.objectIsNull(faultInfo.getGzSbName1())) {
	            		sbN=sbN+faultInfo.getGzSbName1();
	            	}
	            	if(!HandlerNullUtils.objectIsNull(faultInfo.getGzSbName2())) {
	            		sbN=sbN+"-"+faultInfo.getGzSbName2();
	            	}
	            	if(!HandlerNullUtils.objectIsNull(faultInfo.getGzSbName3())) {
	            		sbN=sbN+"-"+faultInfo.getGzSbName3();
	            	}
	            	faultInfo.setGzSb(sbN);
	            }else {
	            	  faultInfo.setGzSb("--");
	            }

	        //故障经纬度
	        if (!HandlerNullUtils.objectIsNull(faultInfo.getFaultLocation())) {
	            //故障地点找不到就去故障描述里面找   聚群提供的地点都是   数字代号要转码
	            Jedis jedis = null;
	            try {
	                jedis = JedisUtilProxy.getJedis();
	            } catch (JedisNotInitializeException e) {
	                e.printStackTrace();
	            }
	            //redis持久化的  车站信息
	            String lineObjectJsonString = jedis.get("stationInfoList");
	            List<StationInfo> list = JSONArray.parseArray(lineObjectJsonString, StationInfo.class);
	            jedis.close();
	            for (StationInfo stationInfo : list) {
	                if (stationInfo.getZhandianId().equals(faultInfo.getFaultLocation())) {
	                    faultInfo.setFaultLocation(stationInfo.getZhandianName());
	                }
	            }
	            locationService.fillLocationOfFaultInfoSingle(faultInfo);
	        }
	        
	        if(!HandlerNullUtils.objectIsNull(faultInfo.getGzFlag())) {
	        	String gzflag = faultInfo.getGzFlag();
	        	 List<JqGzFlag> jqGzFlagList = (List<JqGzFlag>) GuavaCacheUtil
	                        .get("jqGzFlags");
	        	 for(JqGzFlag jqGzFlag:jqGzFlagList) {
	        		 if(faultInfo.getGzFlag().equals(jqGzFlag.getStatusId())) {
	        			 faultInfo.setGzFlag(jqGzFlag.getStatusName());
	        		 }
	        	 }
	        }
        }
        return faultInfo;
    }

    @Override
	@DS("slave_1")
    public List<FaultInfo> getResolveRtFaultListInfo() {

        return faultMapper.getResolveRtFaultListInfo();
    }

    @Override
    @DS("slave_2")
    public List<FaultInfo> getResolveHisFaultListInfo(Map<String, Object> mapIn) {

        return faultMapper.getResolveHisFaultListInfo(mapIn);
    }

    @Override
    @DS("slave_1")
    public List<FaultInfo> getUnResolveRtFaultListInfo() {

        return faultMapper.getUnResolveRtFaultListInfo();
    }

    @Override
    @DS("slave_2")
    public List<FaultInfo> getUnResolveHisFaultListInfo(Map<String, Object> mapIn) {

        return faultMapper.getUnResolveHisFaultListInfo(mapIn);
    }
    
    @Override
    @DS("slave_2")
    public List<FaultInfo> getQueryhistoryFaultListInfo(Map<String, Object> mapIn) {
    	
        return faultMapper.getQueryhistoryFaultListInfo(mapIn);
    }

    @Override
    @DS("master")
    public List<FaultInfo> getTodayFaultInfoFromOracle() {

        return faultMapper.getTodayFaultInfoFromOracle();
    }

    @Override
    @DS("slave_1")
    public List<FaultInfo> getTodayFaultInfoFromMysql() {

        return faultMapper.getTodayFaultInfoFromMysql();
    }

    @Override
    @DS("slave_1")
    public void addOrUpdateFaultInfoToMysql(List<FaultInfo> faultInfoList) {

        faultMapper.addOrUpdateFaultInfoToMysql(faultInfoList);
    }

    @Override
    @DS("master")
    public List<PictureInfo> getFaultPictureListInfo(String faultId) {

        List<PictureInfo> pictureInfoList = new ArrayList<PictureInfo>();

        List<FaultProcessInfo> pictureProcessList = faultMapper.getFaultPictureListInfo(faultId);
        if (!HandlerNullUtils.objectIsNull(pictureProcessList)) {
            for (FaultProcessInfo faultProcessInfo : pictureProcessList) {
            	
            	if(!(HandlerNullUtils.objectIsNull(faultProcessInfo.getUploadFiledata()))) {
            		
            		if(!faultProcessInfo.getUploadFiledata().trim().isEmpty()) {
     
		                if (!"[]".equals(faultProcessInfo.getUploadFiledata())&&!faultProcessInfo.getUploadFiledata().contains(".mp4")) {
		                    java.util.List<PictureInfo> list = getListFromJson(faultProcessInfo.getUploadFiledata(), PictureInfo[].class);
		                    if(!HandlerNullUtils.objectIsNull(list)) {
			                    list.forEach(Pic -> {
			                        Pic.setFileUrl("http://172.20.41.24:9080/wbpj/RP/MA/uploadjsp/downLoad2.jsp?url=" + Pic.getFileUrl());
			                        pictureInfoList.add(Pic);
			                    });
		                    }
		                }
               		}
            	}
            }
        }
        return pictureInfoList;
    }

    @Override
    @DS("slave_1")
    public Map<String, Object> getFaultDisposeTime(String faultId) {

        return faultMapper.getFaultDisposeTime(faultId);

    }

    @Override
    @DS("slave_1")
    public Map<String, Object> getFaultRDTime(String faultId) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String answerTime = "";
        String disposeTime = "";

        Map<String, Object> RDTime = new HashMap<>();

        Map<String, Object> fmap = faultMapper.getFaultDisposeTime(faultId);
        List<FaultTime> faultTimes = faultMapper.getFaultResponseTime(faultId);


        String faultTime = (String) fmap.get("faultTime");//获取故障报警时间字符串

        //统一格式
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime ldt = LocalDateTime.parse(faultTime, dtf);
        DateTimeFormatter fa = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String faultTime1 = ldt.format(fa);

        //遍历响应时间点和故障处理完成时间点
        for (FaultTime faultTime2 : faultTimes) {
            if (null != faultTime2.getDisposeTime()) {
                disposeTime = faultTime2.getDisposeTime(); //处置时间
                answerTime = faultTime2.getAnswerTime(); //响应时间
                long between = 0;
                long between2 = 0;
                try {
                    between = format.parse(answerTime).getTime() - format.parse(faultTime1).getTime();
                    between2 = format.parse(disposeTime).getTime() - format.parse(answerTime).getTime();
                } catch (Exception e) {
                    RDTime.put("ResponseTime", "时间异常");
                    RDTime.put("DisposeTime", "时间异常");

                }
                String xyTime = (between / (1000 * 60)) + "min";
                String czTime = (between2 / (1000 * 60)) + "min";

                RDTime.put("ResponseTime", xyTime);
                RDTime.put("DisposeTime", czTime);
            } else {
                answerTime = faultTime2.getAnswerTime();
                long between = 0;
                try {
                    between = format.parse(answerTime).getTime() - format.parse(faultTime1).getTime();
                } catch (Exception e) {
                    RDTime.put("ResponseTime", "时间异常");
                }
                String xyTime = (between / (1000 * 60)) + "min";
                RDTime.put("ResponseTime", xyTime);
                RDTime.put("DisposeTime", "--:--");
            }

        }
        return RDTime;
    }

    public static <T> java.util.List<T> getListFromJson(String json, Class<T[]> clazz) {
        try {
            T[] arr = new Gson().fromJson(json, clazz);
            return Arrays.asList(arr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    @Override
    @DS("slave_1")
    public Map<String,Object> faultProcessingFlowInfoById(String faultId){
    	 return null;
    }
    
    @Override
    @DS("master")
    public List<User> getHanderFaultUserInfo(String faultId){
    	return faultMapper.getHanderFaultUserInfo(faultId);
    }
    
    @Override
    @DS("slave_1")
    public List<FlowMajor> getFlowMajorStatu(String faultId,String tag) {
        Map<String,String> maps = new HashMap<>();
        maps.put("faultId",faultId);
        maps.put("tag",tag);
        return faultMapper.getFlowMajorStatu(maps);
    }

    @Override
    @DS("slave_1")
    public List<FlowMajor> getFlowMajorAll(String faultId) {
	   return faultMapper.getFlowMajorAll(faultId);
    }


    @Override
    @DS("slave_1")
    public List<Integer> getFlowAllMajor(String faultId) {
	    return faultMapper.getFlowAllMajor(faultId);
    }
    
    @Override
    @DS("slave_1")
    public Integer getAnswerTimeDiff(String faultId) {
        return faultMapper.getAnswerTimeDiff(faultId);
    }

    @Override
    @DS("slave_1")
    public Integer getDisposeTimeDiff(String faultId) {
        return faultMapper.getDisposeTimeDiff(faultId);
    }
    
    @Override
    @DS("slave_1")
    public List<FlowText> getFaultPlanShow(Map<String, String> map) {
    	return faultMapper.getFaultPlanShow(map);
    }
    
}
